package com.kevis.zhunblog.admin.security.config;

import com.kevis.webCommon.secure.support.SecureCaptchaSupport;
import com.kevis.zhunblog.admin.handler.SecureLogoutHandler;
import com.kevis.zhunblog.admin.security.service.UserPermissionEvaluator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.session.HttpSessionEventPublisher;

import javax.annotation.Resource;

/**
 * Security 扩展配置
 *
 * @Author kevis
 * @Date 2023/3/28 11:31
 */
@Configuration
public class SecureExtendConfiguration {

    @Autowired
    private UserPermissionEvaluator userPermissionEvaluator;

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher(){
        return new HttpSessionEventPublisher();
    }

    @Bean
    public SecureLogoutHandler secureLogoutHandler(HttpSessionEventPublisher httpSessionEventPublisher){
        return new SecureLogoutHandler(httpSessionEventPublisher);
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        InMemoryTokenRepositoryImpl tokenRepository = new InMemoryTokenRepositoryImpl();
        //JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        // 赋值数据源
        //tokenRepository.setDataSource(manageDataSource());
        // 自动创建表,第一次执行会创建，以后要执行就要删除掉！
//        tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }

    @Bean
    public SecureCaptchaSupport secureCaptchaSupport(){
        return new SecureCaptchaSupport();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 定义默认的权限管理为自定义实现
     * @return
     */
    @Bean
    public DefaultWebSecurityExpressionHandler userSecurityExpressionHandler() {
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(userPermissionEvaluator);
        return handler;
    }
}
